package com.leff.cards.entity;

import java.util.ArrayList;
import java.util.Date;

import com.google.appengine.api.datastore.Entity;
import com.leff.cards.Dictionary;
import com.leff.cards.request.Request.Parameter;

public class User extends EntityWrapper {

	public static final String KIND = "User";
	
	public User(long fbid, String displayName) {
		super(KIND);
		
		setFbId(fbid);
		setDisplayName(displayName);
		setLastLogin(new Date());
	}
	public User(Entity E) {
		super(E);
	}
	
	public void setFbId(long fbid) {
		put(Parameter.FB_ID, fbid);
	}
	public Long getFbId() {
		return (Long)get(Parameter.FB_ID);
	}
	
	private void setDisplayName(String name) {
		put(Parameter.NAME, name);
	}
	public String getDisplayName() {
		return (String)get(Parameter.NAME);
	}
	
	public void addDeviceId(String gcmId) {
		
		ArrayList<String> ids = getDeviceIds();
		if(!ids.contains(gcmId)) {
			ids.add(gcmId);
			put(Parameter.GCM_ID, ids);
		}
	}
	public void replaceDeviceId(String oldId, String newId) {
		ArrayList<String> ids = getDeviceIds();
		int index = ids.indexOf(oldId);
		if(index >= 0) {
			ids.set(index, newId);
			put(Parameter.GCM_ID, ids);
		}
	}
	public void removeDeviceId(String gcmId) {
		ArrayList<String> ids = getDeviceIds();
		ids.remove(gcmId);
		put(Parameter.GCM_ID, ids);
	}
	public ArrayList<String> getDeviceIds() {
		@SuppressWarnings("unchecked")
		ArrayList<String> ids = (ArrayList<String>)get(Parameter.GCM_ID);
		if(ids == null) {
			ids = new ArrayList<String>();
		}
		return ids;
	}
	
	public Long getVersion() {
		Long version = (Long)get(Parameter.VERSION);
		if(version == null) {
			return -1L;
		}
		return (Long)get(Parameter.VERSION);
	}
	public void setVersion(long version) {
		put(Parameter.VERSION, version);
	}
	
	public Date getLastLogin() {
		Date date = (Date)get(Parameter.LAST_LOGIN);
		if(date == null) {
			return new Date();
		}
		return date;
	}
	public void setLastLogin(Date date) {
		put(Parameter.LAST_LOGIN, date);
	}
	
	public Dictionary toJSON() {
		
		Dictionary obj = new Dictionary();
		
		obj.put(Parameter.ID, getId());
		obj.put(Parameter.FB_ID, getFbId());
		obj.put(Parameter.NAME, getDisplayName());
		
		return obj;
	}
}
